#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;

struct student {
    string name;
    int grade;
    int level;
};

int main() {
    int n;
    cin >> n;
    int h2s;
    cin >> h2s;
    student students[n];
    for (int i = 0; i < n; i++) {
        cin >> students[i].name;
        cin >> students[i].grade;
        students[i].level = i;
    }


    if (h2s == 1) {
        sort(students, students + n, [](student s1, student s2) {
            if (s1.grade == s2.grade)
                return s1.level < s2.level;
            else
                return s1.grade < s2.grade;
        });
        for (int i = 0; i < n; i++) {
            cout << students[i].name << " " << students[i].grade << endl;
        }
    } else {
        sort(students, students + n, [](student s1, student s2) {
            if (s1.grade == s2.grade)
                return s1.level < s2.level;
            else
                return s1.grade > s2.grade;
        });
        for (int i = 0; i < n; i++) {
            cout << students[i].name << " " << students[i].grade << endl;
        }
    }

    return 0;
}